from flask import Blueprint,request,jsonify
from utils.comm import send_message,gain_data
from utils.redis import r
from utils.jwt import myjwt
from db import db
import random
import time

admin_user = Blueprint('app',__name__)

# 用户登录
@admin_user.route('/user_login',methods = ['POST','GET'])
def register():
    if request.method == 'POST':
        gain = gain_data()
        print("*********")
        print(gain)
        select_sql = """
            select id,name,password,email from users where email='%s'
        """%(gain['email'])
        res = db.findall(select_sql)
        print(res)
        if res:
            for i in res:
                if i['password'] == gain['password']:
                    return jsonify({'code':200,'matter':"登陆成功",'user':res})
                else:
                    return jsonify({"code":10010,'matter':'密码错误'})
        else:
            sql = """
                insert into users(id,name,password,email) values(0,'%s','%s','%s')
            """%(gain['name'],gain['password'],gain['email'])
            db.insert(sql)
            select_sql = """
                select id,name,password,email from users where email='%s'
            """%(gain['email'])
            res = db.findall(select_sql)
            return jsonify({'code':200,'user':res,'matter':'登陆成功'})
    else:
        pass

# 验证手机号
@admin_user.route('/mobile',methods=['POST'])
def mobile():
    gain = gain_data()
    sql = """
        select *from users where name='%s'
    """%(gain['mobile'])
    res = db.findall(sql)
    if res:
        return jsonify({'code':10010})
    return jsonify({'code':200})

# 获取验证码
@admin_user.route('/sendsms')
def aa():
    mobile = request.args.get('mobile')
    code = random.randint(100000,999999)
    gain = send_message(mobile,code,1)
    if gain:
        r.str_set(mobile,code,60)
        return jsonify({'code':200,'matter':code})
    else:
        return jsonify({'code':10010})

@admin_user.route('/login',methods=['POST'])
def login():
    #获取手机号和验证码
    data = gain_data()
    # 根据手机号去redis中取验证码
    value = r.str_get(data['mobile'])
    # 没取到直接返回
    if not value:
        return jsonify({"code":10011,'matter':'验证码已经过期，请重新发送'})
	# redis取出来的验证码，输入的对比
    if int(value) == int(data['code']):
        # 对比成功
        # 去数据库查询
        sql = "select * from admin_user where name='%s'"%(data['mobile'])
        res = db.find(sql)
        print("**********")
        print(res)
        # 手机号存在
        if res:
            # 从redis中删除
            r.str_del(data['mobile'])

            sql1 = """

            """

            starttime = time.time()
            # 生成token返回
            token = myjwt.jwt_encode({'data':{'username':data['mobile'],'id':res['id'],'iat':starttime,'exp':1500}})
            return jsonify({"code":200,'user':res,'token':token})
        else:
            return jsonify({"code":10013,'matter':'用户不存在'})
    else:
         return jsonify({"code":10012,'matter':'验证码输入错误'})

#在执行接口前调用
# @admin_user.before_request
# def before_request():
#     # print(request.path)
#     #定义一个白名单，把不需要token认证的接口放到列表里
#     list=['/users/login','/users/sendsms']
#     if request.path not in list:
#         #获取token
#         try:
#             token = request.headers['Token']
#         except:
#             return jsonify({"code":403,'matter':'请传递token'})
#         #解密重新对比token
#         newtoken = myjwt.jwt_decode(token)
#         if newtoken and myjwt.check(token,newtoken):
#             pass
#         else:
#             return jsonify({"code":403,'matter':'token错误'})

# 制定vip
@admin_user.route('/vip',methods=['POST','GET'])
def vip():
    if request.method == 'POST':
        gain = gain_data()
        sql = """
            insert into vip_pirce(id,name,money,unit,type) value(0,'%s',%d,%d,%d)
        """%(gain['name'],int(gain['money']),int(gain['unit']),int(gain['type']))
        db.insert(sql)
        return jsonify({"code":200})
    else:
        sql = """
            select *from vip_price
        """
        res = db.findall(sql)
        return jsonify({"code":200,'matter':res})

from utils.comm import get_ali_object
# VIP购买记录
@admin_user.route('/vip_order',methods=['POST','GET'])
def vip_order():
    if request.method == 'POST':
        gain = gain_data()

        # 生成订单号
        dtime = time.strftime('%Y%m%d%H%M%S', time.localtime())
        num = random.randint(100000,999999)
        serial_number = str(num)+gain['user_id']+str(dtime)

        # 查询VIP信息
        sql1 = """
            select *from vip_price where id=%d
        """%(int(gain['id']))
        res1 = db.find(sql1)

        # 查询订单是否存在
        sql2 = """
            select count(id)from vip_order where user_id=%d and vip_id=%d
        """%(int(gain['user_id']),int(gain['id']))
        res2 = db.find(sql2)

        if res2['count(id)']<1:
             # 生成订单
            sql2 = """
                insert into vip_order(id,user_id,order_no,vip_id,money,pay_status) value(0,%d,'%s',%d,%d,2)
            """%(int(gain['user_id']),serial_number,int(gain['id']),int(res1['money']))
            db.insert(sql2)
            
            # 查询订单记录
            sql3 = """
                select *from vip_order where user_id=%d and vip_id=%d
            """%(int(gain['user_id']),int(gain['id']))
            res3 = db.find(sql3)
            return jsonify({"code":200,'matter':res3,'user_id':gain['user_id']})
            
        elif res2['count(id)']>=1:
           return jsonify({"code":10020,'matter':'订单已存在'})
    else:
        id = request.args.get('id')
        user_id = request.args.get('user_id')
        print(id,user_id)
        sql = """
            select *from vip_order where id=%d
        """%(int(id))
        res = db.find(sql)
        print(res)
        if res:
            alipay = get_ali_object()

            # 生成支付的url
            query_params = alipay.direct_pay(
                subject="小蜜蜂",  # 商品简单描述
                out_trade_no=res['order_no'],  # 用户购买的商品订单号（每次不一样） 20180301073422891
                total_amount=float(res['money']),  # 交易金额(单位: 元 保留俩位小数)
            )
            pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
            return jsonify({'code':200,'matter':pay_url})
        else:
            return jsonify({"code":10030})

@admin_user.route('/gain')
def gain():
    trade_no = request.args.get('trade_no')
    print("*************************")
    print(trade_no)
    return "OK"

